package com.leantech.android.browser.utils

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.widget.Toast
import androidx.core.content.FileProvider
import java.io.File
import java.io.FileOutputStream

/**
 * date：2023/12/27 17:14
 * desc：
 */
object SaveDrawableImageUtils {
    fun saveDrawableImageToGallery(context: Context, drawableResId: Int) {
        val drawableBitmap = BitmapFactory.decodeResource(context.resources, drawableResId)
        saveBitmapToGallery(context, drawableBitmap)
    }

    private fun saveBitmapToGallery(context: Context, bitmap: Bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            saveBitmapToGalleryQ(context, bitmap)
        } else {
            saveBitmapToGalleryLegacy(context, bitmap)
        }
    }

    private fun saveBitmapToGalleryQ(context: Context, bitmap: Bitmap) {
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, "image_${System.currentTimeMillis()}.jpg")
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
            put(MediaStore.Images.Media.IS_PENDING, 1)
        }

        val contentResolver = context.contentResolver
        val uri =
            contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

        try {
            uri?.let {
                contentResolver.openOutputStream(it)?.use { outputStream ->
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
                }
                contentValues.clear()
                contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                contentResolver.update(uri, contentValues, null, null)
                Toast.makeText(context, "图片已保存", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, "图片保存失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun saveBitmapToGalleryLegacy(context: Context, bitmap: Bitmap) {
        val picturesDirectory =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        val imageFile = File(picturesDirectory, "Image_${System.currentTimeMillis()}.jpg")

        try {
            FileOutputStream(imageFile).use { outputStream ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
                galleryAddPic(context, imageFile)
                Toast.makeText(context, "图片已保存", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, "图片保存失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun galleryAddPic(context: Context, imageFile: File) {
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val contentUri = FileProvider.getUriForFile(
            context,
            "${context.packageName}.fileprovider",
            imageFile
        )
        intent.data = contentUri
        context.sendBroadcast(intent)
    }
}